import { closeDB, getDB } from "@/utils/db";
import { newId } from "@/utils/id";
import { err, ok } from "@/utils/resp";

export async function POST(req: Request) {
  try {
    const imt: SubscribeImport = await req.json();
    const nodes: SubmeNode[] = imt.nodes.map((n) => ({
      type: n.type,
      name: n.name,
      host: n["ws-opts"].headers.Host,
      password: n.password ? n.password! : n.uuid!,
      port: n.port,
      path: n["ws-opts"].path,
    }));

    const db = await getDB();
    if (imt.clear) {
      await db.run("DELETE FROM nodes");
    }
    const sql = `INSERT INTO nodes (id, "type", name, host, port, password, "path") VALUES(?,?,?,?,?,?,?)`;
    const insertedNodes = nodes.map(async (n) => {
      const id = newId();
      const nn = { ...n, id };
      await db.run(
        sql,
        nn.id,
        nn.type,
        nn.name,
        nn.host,
        nn.port,
        nn.password,
        nn.path
      );
      return nn;
    });
    await closeDB();
    return ok({ num: insertedNodes.length });
  } catch (e) {
    return err(e as Error);
  }
}
